/**
 * Copyright (c) 2024,  科泰集团教研团队
 * 版权所有，请勿侵权
 */
package com.ktjiaoyu.ktmall.dao.impl;
import com.ktjiaoyu.ktmall.dao.NewsTypeDao;
import com.ktjiaoyu.ktmall.dao.BaseDao;
import com.ktjiaoyu.ktmall.entity.NewsType;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 新闻分类表
 * @author 科泰集团教研团队
 * @createTime 2024-4-17 20:49:54
 * @lastModify 2024-4-17 20:49:54
 * @version 1.0.0
 */
public class NewsTypeDaoImpl extends BaseDao implements NewsTypeDao {

    @Override
    public List<NewsType> getPage(NewsType entity, Integer pageNo, Integer pageSize) {
        StringBuilder sql = new StringBuilder("select * from kt_news_type where 1=1 ");
        List<Object> params = new ArrayList<>();
        sql.append(createPageCondition(entity, params));
        sql.append(" limit ?, ?");
        params.add((pageNo - 1) * pageSize);
        params.add(pageSize);
        try {
            return executeQuery(sql.toString(), rs -> {
                List<NewsType> list = new ArrayList<>();
                try {
                    while (rs.next()) {
                        list.add(extractNewsType(rs));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return list;
            }, params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public int count(NewsType entity) {
        StringBuilder sql = new StringBuilder("select count(1) from kt_news_type where 1=1 ");
        List<Object> params = new ArrayList<>();
        sql.append(createPageCondition(entity, params));
        try {
            List<Integer> result = executeQuery(sql.toString(), rs -> {
                List<Integer> l = new ArrayList<>();
                try {
                    if (rs.next()) {
                        l.add(rs.getInt(1));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return l;
            }, params.toArray());
            return result.isEmpty() ? 0 : result.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public List<NewsType> getAll() {
        String sql = "select * from kt_news_type";
        try {
            return executeQuery(sql, rs -> {
                List<NewsType> list = new ArrayList<>();
                try {
                    while (rs.next()) {
                        list.add(extractNewsType(rs));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return list;
            });
        } catch (SQLException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    @Override
    public NewsType getById(Long id) {
        String sql = "select * from kt_news_type where id=?";
        try {
            List<NewsType> list = executeQuery(sql, rs -> {
                List<NewsType> l = new ArrayList<>();
                try {
                    while (rs.next()) {
                        l.add(extractNewsType(rs));
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return l;
            }, id);
            return list.isEmpty() ? null : list.get(0);
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    public int insert(NewsType entity) throws SQLException {
        return executeUpdate("INSERT INTO kt_news_type(`typeName`,`remark`) VALUES (?,?);", entity.getTypeName(), entity.getRemark());
    }

    @Override
    public int[] insertBatch(NewsType... entities) {
        int[] rows = null;
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            conn.setAutoCommit(false);
            String sql = "INSERT INTO kt_news_type(`typeName`,`remark`) VALUES (?,?);";
            stmt = conn.prepareStatement(sql);
            for (NewsType entity : entities) {
                if(entity == null){
                    continue;
                }
                int j = 1;
                stmt.setObject(j++, entity.getTypeName());
                stmt.setObject(j++, entity.getRemark());
                stmt.addBatch();
            }
            rows = stmt.executeBatch();
            stmt.clearBatch();
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            if(conn != null){
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return rows;
    }

    @Override
    public int update(NewsType entity) {
        if(entity == null || entity.getId() == null){
            return 0;
        }
        List<Object> params = new ArrayList<>();
        StringBuilder sql = new StringBuilder("UPDATE `kt_news_type` SET ");
        if(entity.getTypeName() != null && !entity.getTypeName().trim().isEmpty()){
            sql.append(" typeName = ? ,");
            params.add(entity.getTypeName());
        }
        if(entity.getRemark() != null && !entity.getRemark().trim().isEmpty()){
            sql.append(" remark = ? ,");
            params.add(entity.getRemark());
        }
        if(sql.lastIndexOf(",") == sql.length()-1){
            sql.deleteCharAt(sql.length()-1);
        }
        sql.append(" WHERE id = ?");
        params.add(entity.getId());
        try {
            return executeUpdate(sql.toString(), params.toArray());
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int deleteByEntity(NewsType entity)  {
        if(entity == null || entity.getId() == null){
            return 0;
        }
        return deleteById(entity.getId());
    }

    @Override
    public int deleteById(Long id) {
        String sql = "DELETE FROM kt_news_type WHERE id=?";
        try {
            return executeUpdate(sql, id);
        } catch (SQLException e) {
            e.printStackTrace();
            return 0;
        }
    }

    @Override
    public int[] deleteBatch(Long... ids) {
        int[] rows = null;
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;
        try {
            conn = getConnection();
            conn.setAutoCommit(false);
            String sql = "DELETE FROM kt_news_type WHERE id=?";
            stmt = conn.prepareStatement(sql);
            for (Long id : ids) {
                if(id == null){
                    continue;
                }
                stmt.setObject(1, id);
                stmt.addBatch();
            }
            rows = stmt.executeBatch();
            stmt.clearBatch();
            conn.commit();
        }catch (Exception e){
            e.printStackTrace();
            if(conn != null){
                try {
                    conn.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }
        }
        return rows;
    }

    private NewsType extractNewsType(ResultSet rs) throws SQLException {
        NewsType newsType = new NewsType();
        newsType.setId(rs.getLong("id"));
        newsType.setTypeName(rs.getString("typeName"));
        newsType.setRemark(rs.getString("remark"));
        return newsType;
    }

    private String createPageCondition(NewsType entity, List<Object> params) {
        String sql = "";
        if(entity != null){
        if(entity.getId() != null){
            sql += " and id = ?";
            params.add(entity.getId());
        }
        if(entity.getTypeName() != null && !entity.getTypeName().trim().isEmpty()){
            sql += " and typeName like concat('%', ? , '%')";
            params.add(entity.getTypeName());
        }
        if(entity.getRemark() != null && !entity.getRemark().trim().isEmpty()){
            sql += " and remark = ?";
            params.add(entity.getRemark());
        }
        }
        return sql;
    }
}
